const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');

// 长期运行的 Python 进程，避免重复启动
let persistentPythonProcess = null;
let processRequestId = 0;
let pendingRequests = new Map();

// 内存监控计数器
let totalProcessedFiles = 0;
const MEMORY_CHECK_INTERVAL = 10; // 每10个文件检查一次内存

// 启动长期运行的 Python 进程
function startPersistentPython() {
  if (persistentPythonProcess && !persistentPythonProcess.killed) {
    return persistentPythonProcess;
  }

  // 确定 Python 可执行文件路径
  let pythonExecutable = 'python';
  const venvPython = path.join(__dirname, 'venv', 'Scripts', 'python.exe');
  
  if (fs.existsSync(venvPython)) {
    pythonExecutable = venvPython;
    console.log('🐍 启动持久化 Python 进程:', pythonExecutable);
  } else {
    // 尝试多种 Python 路径
    const pythonPaths = [
      'python',
      'python3',
      'py'
    ];
    
    for (const pythonPath of pythonPaths) {
      try {
        const { execSync } = require('child_process');
        execSync(`"${pythonPath}" --version`, { stdio: 'ignore', timeout: 5000 });
        pythonExecutable = pythonPath;
        console.log('🐍 找到可用的 Python:', pythonExecutable);
        break;
      } catch (error) {
        // 继续尝试下一个路径
      }
    }
  }

  const scriptPath = path.join(__dirname, 'whisper_persistent.py');
  
  persistentPythonProcess = spawn(pythonExecutable, [scriptPath], {
    stdio: ['pipe', 'pipe', 'pipe'],
    encoding: 'utf8',
    env: { ...process.env, PYTHONIOENCODING: 'utf-8' }
  });

  let outputBuffer = '';
  
  persistentPythonProcess.stdout.on('data', (data) => {
    outputBuffer += data.toString('utf8');
    
    // 查找完整的响应
    let lines = outputBuffer.split('\n');
    outputBuffer = lines.pop(); // 保留不完整的行
    
    lines.forEach(line => {
      if (line.trim()) {
        try {
          const response = JSON.parse(line);
          if (response.request_id !== undefined && pendingRequests.has(response.request_id)) {
            const { resolve, reject } = pendingRequests.get(response.request_id);
            pendingRequests.delete(response.request_id);
            
            if (response.error) {
              reject(new Error(response.error));
            } else {
              resolve(response.result);
            }
          }
        } catch (e) {
          console.warn('解析 Python 响应失败:', line);
        }
      }
    });
  });

  persistentPythonProcess.stderr.on('data', (data) => {
    const stderr = data.toString('utf8');
    // 只显示重要的错误信息，忽略调试信息
    if (stderr.includes('Error') || stderr.includes('Failed') || stderr.includes('Exception')) {
      console.error('Python 进程错误:', stderr);
    }
  });

  persistentPythonProcess.on('close', (code) => {
    console.log(`🔄 Python 进程结束，退出码: ${code}`);
    persistentPythonProcess = null;
    
    // 拒绝所有未完成的请求
    for (const [requestId, { reject }] of pendingRequests) {
      reject(new Error('Python 进程意外结束'));
    }
    pendingRequests.clear();
  });

  persistentPythonProcess.on('error', (error) => {
    console.error('🚨 启动 Python 进程失败:', error);
    persistentPythonProcess = null;
  });

  return persistentPythonProcess;
}

// 获取内存使用情况
function getMemoryUsage() {
  const used = process.memoryUsage();
  return {
    rss: Math.round(used.rss / 1024 / 1024 * 100) / 100,
    heapTotal: Math.round(used.heapTotal / 1024 / 1024 * 100) / 100,
    heapUsed: Math.round(used.heapUsed / 1024 / 1024 * 100) / 100,
    external: Math.round(used.external / 1024 / 1024 * 100) / 100
  };
}

// 内存清理
function forceGarbageCollection() {
  if (global.gc) {
    global.gc();
    console.log('🧹 执行垃圾回收');
  } else {
    console.warn('⚠️  垃圾回收不可用，请使用 --expose-gc 参数启动 Node.js');
  }
}

async function transcribeAudio(audioFilePath) {
  return new Promise((resolve, reject) => {
    try {
      // 检查音频文件是否存在
      if (!fs.existsSync(audioFilePath)) {
        throw new Error(`音频文件不存在: ${audioFilePath}`);
      }

      // 内存监控
      totalProcessedFiles++;
      if (totalProcessedFiles % MEMORY_CHECK_INTERVAL === 0) {
        const memUsage = getMemoryUsage();
        console.log(`📊 内存使用情况 (处理了${totalProcessedFiles}个文件):`);
        console.log(`   RSS: ${memUsage.rss}MB, Heap: ${memUsage.heapUsed}/${memUsage.heapTotal}MB`);
        
        // 如果内存使用过高，执行清理
        if (memUsage.heapUsed > 500) { // 500MB
          console.log('⚠️  内存使用过高，重启 Python 进程');
          if (persistentPythonProcess && !persistentPythonProcess.killed) {
            persistentPythonProcess.kill();
            persistentPythonProcess = null;
          }
          forceGarbageCollection();
        }
      }

      // 确保 Python 进程运行
      const pythonProcess = startPersistentPython();
      if (!pythonProcess) {
        reject(new Error('无法启动 Python 进程'));
        return;
      }

      const requestId = processRequestId++;
      const request = {
        request_id: requestId,
        audio_file: audioFilePath,
        model: 'medium',  // 保持使用 medium 模型
        language: 'zh',
        no_fp16: true  // 禁用 FP16 以避免稳定性问题
      };

      // 存储请求回调
      pendingRequests.set(requestId, { resolve, reject });

      // 设置超时
      const timeout = setTimeout(() => {
        if (pendingRequests.has(requestId)) {
          pendingRequests.delete(requestId);
          reject(new Error('转录超时'));
        }
      }, 120000); // 2分钟超时

      // 发送请求到 Python 进程
      pythonProcess.stdin.write(JSON.stringify(request) + '\n');

      // 清理超时
      const originalResolve = resolve;
      const originalReject = reject;
      
      const wrappedResolve = (result) => {
        clearTimeout(timeout);
        originalResolve(result);
      };
      
      const wrappedReject = (error) => {
        clearTimeout(timeout);
        originalReject(error);
      };
      
      pendingRequests.set(requestId, { resolve: wrappedResolve, reject: wrappedReject });

    } catch (error) {
      console.error('转录失败:', error);
      reject(error);
    }
  });
}

// 导出函数
module.exports = {
  transcribeAudio,
  getMemoryUsage,
  forceGarbageCollection
};

